﻿#include "openclmanager.h"
#include <QDebug>

OpenCLManager::OpenCLManager(QObject *parent) : QObject(parent)
{
}

OpenCLManager::~OpenCLManager()
{
    if(m_initialized) {
        qDebug() << "Releasing OpenCL resources";
    }
}

bool OpenCLManager::initialize()
{
    try {
        // 获取平台列表
        std::vector<cl::Platform> platforms;
        cl::Platform::get(&platforms);

        if(platforms.empty()) {
            qWarning() << "No OpenCL platforms found";
            return false;
        }

        m_platform = platforms[0];
        qDebug() << "Using platform:" << m_platform.getInfo<CL_PLATFORM_NAME>().c_str();

        // 获取设备列表(优先选择GPU)
        std::vector<cl::Device> devices;
        m_platform.getDevices(CL_DEVICE_TYPE_GPU, &devices);

        if(devices.empty()) {
            qWarning() << "No GPU devices found, trying CPU";
            m_platform.getDevices(CL_DEVICE_TYPE_CPU, &devices);

            if(devices.empty()) {
                qWarning() << "No OpenCL devices found";
                return false;
            }
        }

        m_device = devices[0];
        qDebug() << "Using device:" << m_device.getInfo<CL_DEVICE_NAME>().c_str();

        // 创建上下文和命令队列
        m_context = cl::Context(m_device);
        m_queue = cl::CommandQueue(m_context, m_device);

        m_initialized = true;
        return true;

    } catch (const cl::Error &err) {
        qCritical() << "OpenCL error:" << err.what() << "(" << err.err() << ")";
        return false;
    }
}

QString OpenCLManager::getDeviceInfo()
{
    if(!m_initialized) return "OpenCL not initialized";

    QString info;
    info += QString("Platform: %1\n").arg(m_platform.getInfo<CL_PLATFORM_NAME>().c_str());
    info += QString("Device: %1\n").arg(m_device.getInfo<CL_DEVICE_NAME>().c_str());
    info += QString("Max compute units: %1\n").arg(m_device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>());
    info += QString("Max work group size: %1\n").arg(m_device.getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>());

    return info;
}
